﻿
// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

$().ready(function () {
    $('.button').button();
    $('form').submit(function (event) {
        event.preventDefault();
    });
    var testsGrid = setUpTestsGrid($('#testsGrid'));
});

// Sets up the sample grid
function setUpTestsGrid($gridSelector) {
    var columns = [
        { id: "Name", name: "Name", field: "Name", width: 400, sortable: true },
    //{ id: "Description", name: "Description", field: "Description", width: 200, sortable: true },
        {id: "buttons", name: "", field: "", width: 500, sortable: false, formatter: CellButtonFormatter, buttons: ["Edit", "Approvals", "Results", "Delete"] }
    ];

    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

    grid.updateHeaderRow();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $('.slick-cell-button').button();
    });
    block({ element: $gridSelector, text: 'Loading' });
    $.getJSON('/TestManagement/ListTests', function (response) {
        if (response.Result)
            grid.dataView.setItems(response.Data);
        else {
            alert(response.Data);
        }
    });
    unblock({ element: $gridSelector });

    setUpAddTestDialog(grid);
    setUpDeleteTestDialog();
    setUpEditTestDialog($gridSelector, grid);

    setUpResultsDialog($gridSelector, grid);
    setUpApprovalsDialog($gridSelector, grid);

    // Return the grid object so we can store it in a variable
    return grid;

    function setUpAddTestDialog(testsGrid) {
        var $dialog = $('#addTestDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 450,
            height: 150,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        // Post to the server
                        $.post('/TestManagement/CreateTest',
                        // Set up the data to transfer
                           extractFormData($('#addTestForm')),
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.addItem(response.Data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#addTestForm'));

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });
                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#addTestForm'));

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#addTestButton').click(function () {
            $dialog.dialog('open');
        });
    }

    function setUpEditTestDialog($testGridSelector, testsGrid) {
        var $dialog = $('#editTestDialog');

        var columns = [
            { id: "Number", name: "#", field: "Number", width: 40, sortable: false, behavior: "selectAndMove", cssClass: "cell-reorder" },
            { id: "Text", name: "Text", field: "Text", width: 360, sortable: false, behavior: "selectAndMove", cssClass: "cell-reorder" },
            { id: "buttons", name: "", field: "", width: 160, sortable: false, formatter: CellButtonFormatter, buttons: ["Edit", "Delete"] }
        ];

        // Set some additional options
        var options = $.extend(true, {}, defaultGridOptions);
        options.hasHeaderFilters = true;

        var $gridSelector = $('#editTest_questionsGrid');
        // Create the grid
        var grid = new Slick.Grid($gridSelector, [], columns, options);
        grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

        grid.setSelectionModel(new Slick.RowSelectionModel());

        var moveRowsPlugin = new Slick.RowMoveManager();

        moveRowsPlugin.onBeforeMoveRows.subscribe(function (e, data) {
            for (var i = 0; i < data.rows.length; i++) {
                // no point in moving before or after itself
                if (data.rows[i] == data.insertBefore || data.rows[i] == data.insertBefore - 1) {
                    e.stopPropagation();
                    return false;
                }
            }
            return true;
        });

        moveRowsPlugin.onMoveRows.subscribe(function (e, args) {
            var extractedRows = [], left, right;
            var rows = args.rows;
            var insertBefore = args.insertBefore;
            var data = grid.dataView.getItems();
            left = data.slice(0, insertBefore);
            right = data.slice(insertBefore, data.length);

            for (var i = 0; i < rows.length; i++) {
                extractedRows.push(data[rows[i]]);
            }

            rows.sort().reverse();

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row < insertBefore) {
                    left.splice(row, 1);
                } else {
                    right.splice(row - insertBefore, 1);
                }
            }
            data = left.concat(extractedRows.concat(right));
            for (var i = 0; i < data.length; i++)
                data[i].Number = i + 1;

            grid.dataView.setItems(data);

            var selectedRows = [];
            for (var i = 0; i < rows.length; i++)
                selectedRows.push(left.length + i);
            grid.resetActiveCell();

            //        grid.setData(data);
            grid.setSelectedRows(selectedRows);
            grid.render();
        });

        grid.registerPlugin(moveRowsPlugin);

        grid.onDragInit.subscribe(function (e, dd) {
            // prevent the grid from cancelling drag'n'drop by default
            e.stopImmediatePropagation();
        });

        grid.updateHeaderRow();

        // Make the grid buttons use jQuery UI
        grid.onRender.subscribe(function (e, args) {
            $('.slick-cell-button').button();
        });
        setUpAddQuestionDialog(grid);
        setUpDeleteQuestionDialog($gridSelector, grid);
        setUpEditQuestionDialog($gridSelector, grid);

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var data = extractFormData($('#editTestForm'));
                        data.QuestionsOrder = [];
                        var questions = grid.dataView.getItems();
                        for (var i = 0; i < questions.length; i++)
                            data.QuestionsOrder.push(questions[i].Id);
                        // Post to the server
                        $.ajax({
                            url: '/TestManagement/UpdateTest',
                            type: 'POST',
                            contentType: 'application/json; charset=utf-8',
                            data: JSON.stringify(data),
                            success: function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    testsGrid.dataView.updateItem(data.Id, data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($('#editTestForm'));

                                grid.dataView.setItems({});
                                // Close the dialog
                                $this.dialog('close');
                            }
                        }).error(function () {
                            // Remove the "saving" block
                            unblock({ element: $this });
                            // Let the user know an error occurred.
                            alert("An error occurred while saving your info. Please refresh the page and try again.");
                        });

                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($('#editTestForm'));

                            grid.dataView.setItems({});

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $(document).on('click', $testGridSelector.selector + ' .slick-cell-button-Edit', function () {
            $dialog.dialog('open');
            var row = testsGrid.getDataItem(testsGrid.getActiveCell().row);

            $('#editTestForm').find('input, select').each(function () {
                $(this).val(row[this.name]);
            });
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/TestManagement/ListQuestionsAndAnswers/' + testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
            function (response) {
                if (response.Result) {
                    grid.dataView.setItems(response.Data);
                    grid.dataView.refresh();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });

        function setUpEditQuestionDialog($questionsGridSelector, questionsGrid) {
            var $dialog = $('#editQuestionDialog');

            var columns = [
                { id: "Number", name: "#", field: "Number", width: 40, sortable: false, behavior: "selectAndMove", cssClass: "cell-reorder" },
                { id: "Text", name: "Text", field: "Text", width: 360, sortable: false, behavior: "selectAndMove", cssClass: "cell-reorder" },
                { id: "buttons", name: "", field: "", width: 155, sortable: false, formatter: CellButtonFormatter, buttons: ["Edit", "Delete"] }
            ];

            // Set some edititional options
            var options = $.extend(true, {}, defaultGridOptions);
            options.hasHeaderFilters = true;

            var $gridSelector = $('#editQuestion_answersGrid');
            // Create the grid
            var grid = new Slick.Grid($gridSelector, [], columns, options);
            grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

            grid.setSelectionModel(new Slick.RowSelectionModel());

            var moveRowsPlugin = new Slick.RowMoveManager();

            moveRowsPlugin.onBeforeMoveRows.subscribe(function (e, data) {
                for (var i = 0; i < data.rows.length; i++) {
                    // no point in moving before or after itself
                    if (data.rows[i] == data.insertBefore || data.rows[i] == data.insertBefore - 1) {
                        e.stopPropagation();
                        return false;
                    }
                }
                return true;
            });

            moveRowsPlugin.onMoveRows.subscribe(function (e, args) {
                var extractedRows = [], left, right;
                var rows = args.rows;
                var insertBefore = args.insertBefore;
                var data = grid.dataView.getItems();
                left = data.slice(0, insertBefore);
                right = data.slice(insertBefore, data.length);

                for (var i = 0; i < rows.length; i++) {
                    extractedRows.push(data[rows[i]]);
                }

                rows.sort().reverse();

                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    if (row < insertBefore) {
                        left.splice(row, 1);
                    } else {
                        right.splice(row - insertBefore, 1);
                    }
                }
                data = left.concat(extractedRows.concat(right));
                for (var i = 0; i < data.length; i++)
                    data[i].Number = i + 1;

                grid.dataView.setItems(data);

                var selectedRows = [];
                for (var i = 0; i < rows.length; i++)
                    selectedRows.push(left.length + i);
                grid.resetActiveCell();
                grid.setSelectedRows(selectedRows);
                grid.render();
            });

            grid.registerPlugin(moveRowsPlugin);

            grid.updateHeaderRow();

            setUpAddAnswerDialog(grid);
            setUpDeleteAnswerDialog($gridSelector, grid);
            setUpEditAnswerDialog($gridSelector, grid);
            // Make the grid buttons use jQuery UI
            grid.onRender.subscribe(function (e, args) {
                $('.slick-cell-button').button();
            });
            var $form = $('#editQuestionForm');
            $dialog.dialog({
                modal: true,
                resizable: false,
                autoOpen: false,
                width: 600,
                height: 600,
                buttons:
                    {
                        OK: function () {
                            var $this = $(this);
                            var answers = grid.dataView.getItems();
                            if (answers.length == 0) {
                                alert("A question must have at least 2 answers!");
                                return;
                            }
                            // Show a saving indicator
                            block({ element: $this, text: 'Saving' });
                            var data = extractFormData($form);
                            data.AnswersOrder = [];
                            data.Id = questionsGrid.getDataItem(questionsGrid.getActiveCell().row).Id;
                            data.CorrectAnswerId = $('#editQuestion_correctAnswer').val();
                            for (var i = 0; i < answers.length; i++)
                                data.AnswersOrder.push(answers[i].Id);
                            // Post to the server
                            $.ajax({
                                url: '/TestManagement/UpdateQuestion',
                                type: 'POST',
                                contentType: 'application/json; charset=utf-8',
                                data: JSON.stringify(data),
                                success: function (response) {
                                    if (response.Result) {
                                        // If the request succeeded, display the changes
                                        var question = questionsGrid.getDataItem(questionsGrid.getActiveCell().row);
                                        question.Text = data.Text;
                                        question.Answers = grid.dataView.getItems().sort(function (a, b) { return a.Number - b.Number; });
                                        question.CorrectAnswerId = data.CorrectAnswerId;
                                        questionsGrid.invalidate();


                                    } else {
                                        // If it failed, show the error response
                                        alert(response.Data);
                                    }
                                    unblock({ element: $this });
                                    // Clear the fields
                                    clearForm($form);
                                    $('#editQuestion_correctAnswer').empty();

                                    grid.dataView.setItems({});
                                    grid.dataView.refresh();
                                    // Close the dialog
                                    $this.dialog('close');
                                }
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });
                        },
                        Cancel:
                            function () {
                                // Clear the fields
                                clearForm($form);
                                // Clear the grid
                                grid.dataView.setItems({});
                                grid.dataView.refresh();
                                $('#editQuestion_correctAnswer').empty();

                                // Close the dialog box
                                $(this).dialog('close');
                            }
                    }
            });

            $(document).on('click', $questionsGridSelector.selector + ' .slick-cell-button-Edit', function () {
                $dialog.dialog('open');
                var row = questionsGrid.getDataItem(questionsGrid.getActiveCell().row);

                $form.find('input, select').each(function () {
                    $(this).val(row[this.name]);
                });
                grid.dataView.setItems(row.Answers);
                grid.invalidate();
                $('#editQuestion_correctAnswer').empty();
                $.each(row.Answers, function () {
                    $('#editQuestion_correctAnswer')
                        .append('<option value="' + this.Id + '"' + (this.Id == row.CorrectAnswerId ? ' selected="selected"' : '') + '>' + this.Text + "</option>");
                });
            });

            function setUpAddAnswerDialog(answersGrid) {
                var $dialog = $('#addAnswerDialog');
                var $form = $('#addAnswerForm');
                $dialog.dialog({
                    modal: true,
                    resizable: false,
                    autoOpen: false,
                    width: 450,
                    height: 150,
                    buttons:
                        {
                            OK: function () {
                                var $this = $(this);
                                // Show a saving indicator
                                block({ element: $this, text: 'Saving' });

                                var data = extractFormData($form);
                                data.QuestionId = questionsGrid.getDataItem(questionsGrid.getActiveCell().row).Id;
                                // Post to the server
                                $.post('/TestManagement/CreateAnswer',
                                // Set up the data to transfer
                                    data,
                                // This function gets called if the server successfully returns a response. 
                                // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                                    function (response) {
                                        if (response.Result) {
                                            // If the request succeeded, display the changes
                                            answersGrid.dataView.addItem(response.Data);
                                            $('#editQuestion_correctAnswer').append('<option value="' + response.Data.Id + '">' + response.Data.Text + "</option>");
                                            if ($('#editQuestion_correctAnswer').children().length == 1)
                                                $('#editQuestion_correctAnswer').children().attr('selected', 'selected');

                                        } else {
                                            // If it failed, show the error response
                                            alert(response.Data);
                                        }
                                        unblock({ element: $this });
                                        // Clear the fields
                                        clearForm($form);

                                        // Close the dialog
                                        $this.dialog('close');
                                    }).error(function () {
                                        // Remove the "saving" block
                                        unblock({ element: $this });
                                        // Let the user know an error occurred.
                                        alert("An error occurred while saving your info. Please refresh the page and try again.");
                                    });
                                // Clear the fields
                                clearForm($form);
                                // Close the dialog box
                                $(this).dialog('close');
                            },
                            Cancel:
                                function () {
                                    // Clear the fields
                                    clearForm($form);
                                    // Close the dialog box
                                    $(this).dialog('close');
                                }
                        }
                });

                $('#editQuestion_createAnswer').click(function () {
                    $dialog.dialog('open');
                });
            }

            function setUpEditAnswerDialog($answersGridSelector, answersGrid) {
                var $dialog = $('#editAnswerDialog');
                var $form = $('#editAnswerForm');
                $dialog.dialog({
                    modal: true,
                    resizable: false,
                    autoOpen: false,
                    width: 450,
                    height: 150,
                    buttons:
                        {
                            OK: function () {
                                var $this = $(this);
                                // Show a saving indicator
                                block({ element: $this, text: 'Saving' });

                                var data = extractFormData($form);
                                data.id = answersGrid.getDataItem(answersGrid.getActiveCell().row).Id;
                                // Post to the server
                                $.post('/TestManagement/UpdateAnswer',
                                // Set up the data to transfer
                                    data,
                                // This function gets called if the server successfully returns a response. 
                                // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                                    function (response) {
                                        if (response.Result) {
                                            // If the request succeeded, display the changes
                                            answersGrid.getDataItem(answersGrid.getActiveCell().row).Text = data.Text;
                                            answersGrid.invalidate();
                                            $('#editQuestion_correctAnswer option[value="' + response.Data.Id + '"]').text(response.Data.Text);
                                        } else {
                                            // If it failed, show the error response
                                            alert(response.Data);
                                        }
                                        unblock({ element: $this });
                                        // Clear the fields
                                        clearForm($form);

                                        // Close the dialog
                                        $this.dialog('close');
                                    }).error(function () {
                                        // Remove the "saving" block
                                        unblock({ element: $this });
                                        // Let the user know an error occurred.
                                        alert("An error occurred while saving your info. Please refresh the page and try again.");
                                    });
                                // Clear the fields
                                clearForm($form);
                                // Close the dialog box
                                $(this).dialog('close');
                            },
                            Cancel:
                                function () {
                                    // Clear the fields
                                    clearForm($form);
                                    // Close the dialog box
                                    $(this).dialog('close');
                                }
                        }
                });

                $(document).on('click', $answersGridSelector.selector + ' .slick-cell-button-Edit', function () {
                    $dialog.dialog('open');
                    var row = answersGrid.getDataItem(answersGrid.getActiveCell().row);

                    $form.find('input, select').each(function () {
                        $(this).val(row[this.name]);
                    });
                });
            }
        }
    }
    function setUpDeleteTestDialog() {
        var $dialog = $('#deleteTestDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var id = grid.getDataItem(grid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/TestManagement/DeleteTest',
                        // Set up the data to transfer
                            {id: id },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.deleteItem(id);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Delete', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);
            $('#testName').text(row.Name);
            $dialog.dialog('open');
        });
    }

    //#region Questions

    function setUpAddQuestionDialog(questionsGrid) {
        var $dialog = $('#addQuestionDialog');

        var $form = $('#addQuestionForm');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 450,
            height: 150,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });

                        var data = extractFormData($form);
                        data.TestId = grid.getDataItem(grid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/TestManagement/CreateQuestion',
                        // Set up the data to transfer
                           data,
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    questionsGrid.dataView.addItem(response.Data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });
                                // Clear the fields
                                clearForm($form);

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });
                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            clearForm($form);

                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#editTest_createQuestion').click(function () {
            $dialog.dialog('open');
        });

    }

    function setUpDeleteQuestionDialog($questionsGridSelector, questionsGrid) {
        var $dialog = $('#deleteQuestionDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var id = questionsGrid.getDataItem(questionsGrid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/TestManagement/DeleteQuestion',
                        // Set up the data to transfer
                            {id: id },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    questionsGrid.dataView.setItems(response.Data);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });
        $(document).on('click', $questionsGridSelector.selector + ' .slick-cell-button-Delete', function () {
            var row = questionsGrid.getDataItem(questionsGrid.getActiveCell().row);
            $('#questionText').text(row.Number + ". " + row.Text);
            $dialog.dialog('open');
        });
    }
    //#endregion

    //#region Answers
    function setUpDeleteAnswerDialog($answersGridSelector, answersGrid) {
        var $dialog = $('#deleteAnswerDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            buttons:
            {
                OK: function () {
                    var $this = $(this);
                    // Show a saving indicator
                    block({ element: $this, text: 'Saving' });
                    var id = answersGrid.getDataItem(answersGrid.getActiveCell().row).Id;
                    // Post to the server
                    $.post('/TestManagement/DeleteAnswer',
                    // Set up the data to transfer
                        {id: id },
                    // This function gets called if the server successfully returns a response. 
                    // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                        function (response) {
                            if (response.Result) {
                                // If the request succeeded, display the changes
                                answersGrid.dataView.setItems(response.Data);
                            } else {
                                // If it failed, show the error response
                                alert(response.Data);
                            }
                            unblock({ element: $this });

                            // Close the dialog
                            $this.dialog('close');
                        }).error(function () {
                            // Remove the "saving" block
                            unblock({ element: $this });
                            // Let the user know an error occurred.
                            alert("An error occurred while saving your info. Please refresh the page and try again.");
                        });
                },
                Cancel:
                    function () {
                        // Close the dialog box
                        $(this).dialog('close');
                    }
            }
        });
        $(document).on('click', $answersGridSelector.selector + ' .slick-cell-button-Delete', function () {
            var row = answersGrid.getDataItem(answersGrid.getActiveCell().row);
            $('#answerText').text(row.Number + ". " + row.Text);
            $dialog.dialog('open');
        });
    }
    //#endregion Answers

    //#region Results
    function setUpResultsDialog($testsGridSelector, testsGrid) {
        var $dialog = $('#testResultsDialog');
        var $gridSelector = $('#testResultsGrid');
        var columns = [
            { id: "Name", name: "Employee", field: "Name", width: 200, sortable: true },
            { id: "Score", name: "Score", field: "Score", width: 100, sortable: true },
            { id: "buttons", name: "", field: "", width: 200, sortable: false, formatter: CellButtonFormatter, buttons: ["Pass", "Results"] }
        ];

        // Set some additional options
        var options = $.extend(true, {}, defaultGridOptions);
        options.hasHeaderFilters = true;

        // Create the grid
        var grid = new Slick.Grid($gridSelector, [], columns, options);
        grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

        grid.updateHeaderRow();

        // Make the grid buttons use jQuery UI
        grid.onRender.subscribe(function (e, args) {
            $('.slick-cell-button').button();
        });

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        grid.dataView.setItems({});
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
        });

        setUpEmployeeResultsDialog($gridSelector, grid);

        $(document).on('click', $testsGridSelector.selector + ' .slick-cell-button-Results', function () {
            $dialog.dialog('option', { title: "Results - " + testsGrid.getDataItem(testsGrid.getActiveCell().row).Name });
            $dialog.dialog('open');
            var row = testsGrid.getDataItem(testsGrid.getActiveCell().row);

            //$('#testResults_name').text(row.Name);
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/TestManagement/ListTestResults/' + testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
            function (response) {
                if (response.Result) {
                    grid.dataView.setItems(response.Data);
                    grid.dataView.refresh();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });
        // Return the grid object so we can store it in a variable
        return grid;

        //#region Functions
        function setUpEmployeeResultsDialog($resultsGridSelector, resultsGrid) {
            var $dialog = $('#employeeResultsDialog');
            
            $dialog.dialog({
                modal: true,
                resizable: false,
                autoOpen: false,
                width: 600,
                height: 600,
                buttons:
                {
                    OK: function () {
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
            });
            $(document).on('click', $resultsGridSelector.selector + ' .slick-cell-button-Results', function () {
                $('#questionsAndAnswers').empty();
                $dialog.dialog('option', { title: "Results - " + testsGrid.getDataItem(testsGrid.getActiveCell().row).Name + " - " + resultsGrid.getDataItem(resultsGrid.getActiveCell().row).Name });
                $dialog.dialog('open' );

                block({ element: $gridSelector, text: 'Loading' });
                $.getJSON('/TestManagement/ListEmployeeTestResults',
                    {
                        testId: testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
                        employeeId: resultsGrid.getDataItem(resultsGrid.getActiveCell().row).Id
                    },
                    function (response) {
                        if (response.Result) {
                            $.each(response.Data, function () {
                                var question = this;
                                var $questionDiv = $(jQuery.validator.format('<div class="questionContainer"><div class="question">{0}. {1}</div></div>', question.Number, question.Text));
                                var $answersList = $('<ol class="answer"></ol>');
                                $.each(question.Answers, function () {
                                    var answer = this;
                                    var $answerHtml = $(jQuery.validator.format('<li>{0}</li>', answer.Text));
                                    if (answer.Id == question.EmployeeAnswerId && answer.Id != question.CorrectAnswerId)
                                        $answerHtml.addClass('wrongAnswer');
                                    if (answer.Id == question.CorrectAnswerId)
                                        $answerHtml.addClass('rightAnswer');
                                    $answersList.append($answerHtml);
                                });
                                $questionDiv.append($answersList);
                                $('#questionsAndAnswers').append($questionDiv);
                            });
                        } else {
                            alert(response.Data);
                            $dialog.dialog('close');
                        }
                    });
                unblock({ element: $gridSelector });
            });
        }
        //#endregion
    }
    //#endregion

    //#region Approvals
    function setUpApprovalsDialog($testsGridSelector, testsGrid) {
        var $dialog = $('#testApprovalsDialog');
        var $gridSelector = $('#testApprovalsGrid');
        var columns = [
            { id: "Employee", name: "Employee", field: "Employee", width: 200, sortable: true },
            {
                id: "buttons",
                name: "",
                field: "",
                width: 200,
                sortable: false,
                formatter: CellButtonFormatter,
                buttons: [{ name: "Approve", enable: 'IsApproved', negateEnable: true }, { name: "Revoke", enable: 'IsApproved' }]
            }
        ];

        // Set some additional options
        var options = $.extend(true, {}, defaultGridOptions);
        options.hasHeaderFilters = true;

        // Create the grid
        var grid = new Slick.Grid($gridSelector, [], columns, options);
        grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));
        grid.updateHeaderRow();

        // Make the grid buttons use jQuery UI
        grid.onRender.subscribe(function (e, args) {
            $('.slick-cell-button').button();
        });

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        grid.dataView.setItems({});
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
        });

        $(document).on('click', $testsGridSelector.selector + ' .slick-cell-button-Approvals', function () {
            $dialog.dialog('option', { title: "Approvals - " + testsGrid.getDataItem(testsGrid.getActiveCell().row).Name });
            $dialog.dialog('open');
            var row = testsGrid.getDataItem(testsGrid.getActiveCell().row);

            $('#testApprovals_name').text(row.Name);
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/TestManagement/ListTestApprovals/' + testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
            function (response) {
                if (response.Result) {
                    grid.dataView.setItems(response.Data);
                    grid.dataView.refresh();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });

        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Approve', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);

            block({ element: $gridSelector, text: 'Loading' });
            $.post('/TestManagement/Approve/',
                {
                    testId: testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
                    employeeId: row.Id
                },
            function (response) {
                if (response.Result) {
                    row.IsApproved = true;
                    grid.invalidate();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Revoke', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);

            block({ element: $gridSelector, text: 'Loading' });
            $.post('/TestManagement/Revoke/',
                {
                    testId: testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
                    employeeId: row.Id
                },
            function (response) {
                if (response.Result) {
                    row.IsApproved = false;
                    grid.invalidate();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });
        // Return the grid object so we can store it in a variable
        return grid;
    }
    //#endregion
}
